﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nox.Amuse.MVVM;
using System.Collections.ObjectModel;
using System.Windows.Controls;
using System.Windows.Documents;

namespace Nox.Amuse.ViewModel
{
    class TabBarViewModel : ObservableObject
    {
        public ObservableCollection<TabViewModel> TabList { get; private set; }

        public TabViewModel SelectedTab
        {
            get { return SelectedTabIndex > -1 ? TabList[SelectedTabIndex] : null; }
        }

        public int SelectedTabIndex
        {
            get { return mySelectedTabIndex; }
            set
            {
                mySelectedTabIndex = value;
                base.RaisePropertyChanged("SelectedTabIndex");
                base.RaisePropertyChanged("SelectedTab");
                App.Messenger.NotifyColleagues(Messages.TabChanged, SelectedTab);
            }
        }
        private int mySelectedTabIndex = -1;

        public TabBarViewModel()
        {
            TabList = new ObservableCollection<TabViewModel>();
            App.Messenger.Register(Messages.StartTestConnection, () => { AddTestTab(); });
            App.Messenger.Register<TabViewModel>(Messages.TabAddRequest, (tvm) => { AddTab(tvm); });
            App.Messenger.Register<TabViewModel>(Messages.TabRemoveRequest, (tvm) => { RemoveTab(tvm); });
        }

        private void AddTab(TabViewModel tvm)
        {
            TabList.Add(tvm);
            base.RaisePropertyChanged("TabList");
            SelectedTabIndex = TabList.Count - 1;
            tvm.Connect();
        }

        private void RemoveTab(TabViewModel tvm)
        {
            if (SelectedTabIndex == -1)
                throw new InvalidOperationException("There are no tabs to remove!");
            if (SelectedTab == tvm || SelectedTabIndex != 0) // If the tab being removed is the current one or not the first
                SelectedTabIndex--; // Reduce the index by 1 (will automatically reduce if the last tab is being removed)
            TabList.Remove(tvm);
        }

        private void AddTestTab()
        {
            TabViewModel tvm = new TabViewModel(new Model.WorldData { Name = "Test Connection", Address = "somewhere.com", Port = 2222 });
            TabList.Add(tvm);
            base.RaisePropertyChanged("TabList");
            SelectedTabIndex = TabList.Count - 1;
            tvm.Connect();
        }
    }
}
